package my.graphicstest;

import java.lang.ref.WeakReference;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.widget.ImageView;

public class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
	private final WeakReference<ImageView> imageViewReference;
	public BitmapWorkerTask(ImageView view){
		imageViewReference =new WeakReference<ImageView>(view);
	}
	@Override
	protected Bitmap doInBackground(String... arg0) {
		// TODO Auto-generated method stub
		String path = arg0[0];
		
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, options);
		
		options.inJustDecodeBounds = false;
		options.inSampleSize = caculateInSampleSize(options,getDisplayMetrics());
		Bitmap bitmap = BitmapFactory.decodeFile(path,options);
		return bitmap;
	}
	
	public Point getDisplayMetrics(){
		Point point = new Point();
		DisplayMetrics metrics =  Resources.getSystem().getDisplayMetrics();
		point.x = metrics.widthPixels;
		point.y = metrics.heightPixels;
		return point;	
	}
	
	public int caculateInSampleSize(BitmapFactory.Options options, Point point){
		int widthRatio,heightRatio;
		widthRatio = Math.round((float)options.outWidth/(float)point.x);
		heightRatio = Math.round((float)options.outHeight/(float)point.y);
		return widthRatio < heightRatio ? widthRatio : heightRatio;
	}
	@Override
	protected void onPostExecute(Bitmap bitmap) {
		if(imageViewReference != null && bitmap != null){
			final ImageView view = imageViewReference.get();
			if(view != null){
				view.setImageBitmap(bitmap);
		}
		}
	}

}
